package com.example.demo.builder;

/**
 * 模拟一个简单的数据库连接池对象
 */
public class SimpleDataSource {

    //数据库连接基本信息
    private String url;
    private String username;
    private String password;

    //连接池数量配置
    private Integer initialSize;
    private Integer maxSize;

    public SimpleDataSource() {
    }

    public SimpleDataSource(String url, String username, String password, Integer initialSize, Integer maxSize) {
        this.url = url;
        this.username = username;
        this.password = password;
        this.initialSize = initialSize;
        this.maxSize = maxSize;
    }

    @Override
    public String toString() {
        return "SimpleDataSource{" +
                "url='" + url + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", initialSize=" + initialSize +
                ", maxSize=" + maxSize +
                '}';
    }

    /**
     * 获取建造者
     * @return
     */
    public static Builder builder(){
        return new Builder();
    }

    /**
     * 建造者类
     */
    public static class Builder{
        //必填部分
        private String url;
        private String username;
        private String password;
        //选填部分（有默认值）
        private Integer initialSize = 10;
        private Integer maxSize = 1000;

        public Builder setUrl(String url) {
            this.url = url;
            return this;
        }

        public Builder setUsername(String username) {
            this.username = username;
            return this;
        }

        public Builder setPassword(String password) {
            this.password = password;
            return this;
        }

        public Builder setInitialSize(Integer initialSize) {
            this.initialSize = initialSize;
            return this;
        }

        public Builder setMaxSize(Integer maxSize) {
            this.maxSize = maxSize;
            return this;
        }

        public SimpleDataSource build() {
            //校验下必填部分
            if (url == null) {
                throw new RuntimeException("url必填");
            }
            if (username == null) {
                throw new RuntimeException("username必填");
            }
            if (password == null) {
                throw new RuntimeException("password必填");
            }
            //创建对象
            return new SimpleDataSource(url, username, password, initialSize, maxSize);
        }
    }

}
